﻿using System.Collections.Generic;

namespace Azalea.ORMap
{
    public class SqlSelect : ISqlSelect
    {
        private readonly CommandBuilder _cmdBuilder;
        private readonly List<string> _fields = new List<string>();
        private string _tableName;

        public SqlSelect(CommandBuilder cmdBuilder)
        {
            _cmdBuilder = cmdBuilder;
        }

        #region ISqlSelect Members

        public ISqlSelect Table(string tableName)
        {
            _tableName = tableName;
            return this;
        }

        public ISqlSelect Count()
        {
            _fields.Clear();
            _fields.Add("count(*)");
            return this;
        }

        public ISqlSelect AllFields()
        {
            _fields.Clear();
            _fields.Add("*");
            return this;
        }

        public ISqlSelect Field(string field)
        {
            _fields.Add(_cmdBuilder.QuotingKeyword(field));
            return this;
        }

        public ISqlSelect Field(string field, string alias)
        {
            _fields.Add(_cmdBuilder.QuotingKeyword(field) + " as " + alias);
            return this;
        }

        public ISqlWhere Where()
        {
            GenerateSql();

            return new SqlWhere(_cmdBuilder, _tableName);
        }

        public ICommandBuilder Done()
        {
            GenerateSql();

            return _cmdBuilder;
        }

        #endregion

        #region private members

        private void GenerateSql()
        {
            _cmdBuilder._sqlBuilder.Append("select ");
            bool commaNeeded = false;
            foreach (string field in _fields)
            {
                if (commaNeeded)
                {
                    _cmdBuilder._sqlBuilder.Append(",");
                }
                _cmdBuilder._sqlBuilder.Append(field);
                commaNeeded = true;
            }
            _cmdBuilder._sqlBuilder.Append(" from ")
                .Append(_cmdBuilder.QuotingKeyword(_tableName));
        }

        #endregion
    }
}